package util;

import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.List;

public class ReflectionUtils {
	public static Object getPropertyValue(Object obj, String propertyName) {
		try {
			Class<? extends Object> objClass = obj.getClass();
			String pn = propertyName.substring(0, 1).toUpperCase()
					+ propertyName.substring(1);
			Method method;
			try {
				method = objClass.getMethod("get" + pn);
			} catch (Exception exGet) {
				method = objClass.getMethod("is" + pn);
			}
			Object value = method.invoke(obj, (Object[]) null);
			return value;
		} catch (Exception exIs) {
			throw new RuntimeException("Property not found " + propertyName,
					exIs);
		}
	}

	@SuppressWarnings("unchecked")
	public static String getPropertyStringValue(Object obj, String propertyName) {
		Object value;
		String[] props = propertyName.split("\\.");
		if (props.length >= 2) {
			value = getPropertyValue(obj, props[0]);				
			for (int i = 1; i < props.length; i++) {
				if (value == null)
					break;
				String string = props[i];
				value = getPropertyValue(value, string);
			}
		} else {
			value = getPropertyValue(obj, propertyName);
		}
		if (value == null) {
			return null;
		}
		String valueStr = value.toString();
		return valueStr;
	}

	public static String[] convertToStringArray(Object obj, String[] properties) {
		String[] propertiesAsString = new String[properties.length];
		for (int i = 0; i < properties.length; i++) {
			propertiesAsString[i] = getPropertyStringValue(obj, properties[i]);
		}
		return propertiesAsString;
	}

	public static String[][] convertListToStringArray(List<Serializable> pojos,
			String[] properties) {
		String[][] listAsArray = new String[pojos.size()][];
		for (int i = 0; i < pojos.size(); i++) {
			listAsArray[i] = convertToStringArray(pojos.get(i), properties);
		}
		return listAsArray;
	}
}
